package com.mjk.common.web.getway.restful.interceptor.type.commons.impl;

import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.tools.gson.GsonUtils;
import com.mjk.common.tools.interceptor.InterceptorChain;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.tools.springextend.BeeApplicationListener;
import com.mjk.common.util.ComputerUtils;
import com.mjk.common.util.HttpUtils;
import com.mjk.common.util.MapUtils;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.web.getway.constns.GetwayConsts;
import com.mjk.common.web.getway.restful.interceptor.GetWayInterceptorReq;
import com.mjk.common.web.getway.restful.interceptor.annotation.BeeGetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptorType;
import com.mjk.common.web.getway.utils.loadbalancer.AbstractLoadBalancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/**
 * 负载均衡拦截器 用于分发配置了evn表的请求
 *  实现应基于nacos的注册中心 获取服务信息
 *  应该后于获取IP（GetWayIpInterceptor）拦截器执行
 */
@BeeGetWayInterceptor(value=5,interceptorType={GetWayInterceptorType.ALL})
public class GetWayLoadBalanceInterceptor implements GetWayInterceptor, BeeApplicationListener {
    @Autowired
    private AbstractLoadBalancer loadBalancer;
    /**
     * 节点端口
     */
    @Value(value = "${server.port:8080}")
    private int nodePort;
    @Override
    public BeeResponse interceptor(GetWayInterceptorReq request, InterceptorChain<GetWayInterceptorReq, BeeResponse> next) {
        String ip = MapUtils.getString( request.getParams(),GetwayConsts.IP);
        String server = loadBalancer.getNextServer(ip);
        if(ObjectUtils.isEmpty(server)) {
            return next.proceed(request);
        }else{
            ComputerUtils.ComputerInfo computerInfo = ComputerUtils.getComputerInfo();
            if(server.equals(computerInfo.getIp()+":"+nodePort)){
                //判断返回的IP地址和端口是不是本机
                return next.proceed(request);
            }
            return doDispath(server,request);//发起负载均衡请求
        }
    }

    /**
     * 请求分发
     */
    public BeeResponse doDispath(String server,GetWayInterceptorReq req){
        String prototol = MapUtils.getString(req.getRestfulParams(),GetwayConsts.PROTOCOL);
        String version = MapUtils.getString(req.getRestfulParams(),GetwayConsts.VERSION);
        String work = MapUtils.getString(req.getRestfulParams(),GetwayConsts.INSTANCE);
        String method = MapUtils.getString(req.getParams(),GetwayConsts.METHOD);
        String url = "http://"+server+"/ld/"+prototol+"/"+version+"/"+work+"?method="+method;
        if(req.getHeadParams().containsKey("content-length")){
            req.getHeadParams().remove("content-length");
        }
        //发起负载均衡调用
        BizLogger.info(loadBalancer.getClass().getName()+"load balance req");
        String result = HttpUtils.httpPost(url,req.getParams(),req.getHeadParams());
        return GsonUtils.json2Bean(result,BeeResponse.class);
    }
}
